<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @change="onSearch()"
      />
      <el-button type="primary" @click="onSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/park/AddEnterprise')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @expand-change="onExpandChange"
        row-key="id"
      >
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="300"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status"> 
                <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="280">
                <template v-slot="{ row: sonRow }">
                  <el-button size="small" type="text">续租</el-button>
                  <el-button size="small" type="text" :disabled="row.status === 3" @click="outRent(row)">退租</el-button>
                  <el-button size="small" type="text" :disabled="row.status !== 3" @click="deleteRent(sonRow, row)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="160" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="text" @click="addRent(row.id)"
              >添加合同</el-button
            >
            <el-button size="small" type="text">查看</el-button>
            <el-button size="small" type="text">编辑</el-button>
            <el-button size="small" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList()"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 50, 100]"
      />
    </div>
  </div>
  <!-- 添加合同弹窗                                                   @close    关闭事件    -->
  <el-dialog
    v-model="rentDialogVisible"
    title="添加合同"
    width="40%"
    @close="closeRent"
  >
    <!-- 使用el-form组件，设置标签位置为顶部 -->
    <el-form
      ref="addFormRef"
      label-position="top"
      :model="rentForm"
      :rules="rentRules"
      style="padding: 6%"
    >
      <!-- 租赁楼宇表单项，使用el-form-item组件，设置标签和属性 -->
      <el-form-item label="租赁楼宇" prop="buildingId">
        <!-- 使用el-select组件，设置楼宇选择框的占位符 -->
        <el-select
          placeholder="请选择楼宇"
          v-model="rentForm.buildingId"
          clearable
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in buildList"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="租赁起止日期" prop="endTime">
        <el-date-picker
          v-model="timeArr"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        />
      </el-form-item>

      <el-form-item label="上传合同" prop="contractId">
        <el-upload
          v-model:file-list="fileList"
          accept=".doc,.pdf"
          @remove="removeUpload"
          :before-upload="beforeUpload"
        >
          <template #trigger>
            <el-button size="small" type="primary">点击上传</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="addRentConfirm()" type="primary">确定</el-button>
      <el-button @click="closeRent()">关闭</el-button>
    </template>
    {{ rentForm }}
  </el-dialog>
</template>

<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import {
  createRentAPI,
  deleteRentAPI,
  getEnterpriseListAPI,
  getRentBuildListAPI,
  getRentListAPI,
  outRentAPI,
} from '@/apis/enterprise';
import type {
  EnterpriseListData,
  Enterprise,
  EnterpriseListParams,
  RentParams,
  RentBuilding,
  Datum,
} from '@/types/enterprise';
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from 'element-plus';
import { ref, watch } from 'vue';

// 表单数据默认值，每次调用，都返回一个新对象
const initRentForm = () => {
  return {
    buildingId: undefined, // 租赁楼宇id
    startTime: '', // 开始日期（不能小于今日日期）
    endTime: '', // 租赁结束日期
    contractUrl: '', // 合同附件url
    contractId: undefined, // 合同附件id
    type: 0, // 操作类型，添加合同0，续签合同1
    enterpriseId: undefined, // 企业id
  };
};
// 添加合同 - 1表单数据
const rentForm = ref<RentParams>(initRentForm()); // 添加合同 - 表单校验
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [{ required: true, message: '请选择楼宇', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择租赁日期', trigger: 'blur' }],
  contractId: [{ required: true, message: '请上传合同文件' }],
});

// 前端自定义的类型，用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList: Datum[];
}

const params = ref<EnterpriseListParams>({
  name: '',
  page: 1,
  pageSize: 10,
});

const list = ref<EnterpriseWithRent[]>([]);
const total = ref(0);
const getList = async () => {
  //     里面传的时ref的值，并不是ref
  const res = await getEnterpriseListAPI(params.value);
  // map 映射数据用于前端展示
  list.value = res.data.rows.map((item) => ({
    ...item,
    rentList: [], // 合同列表默认值，用于嵌套表格渲染
  }));
  total.value = res.data.total;
};
getList();

const onSearch = () => {
  params.value.page = 1;
  getList();
};

const buildList = ref<RentBuilding[]>([]);
// 添加合同
const rentDialogVisible = ref(false);
// 打开弹窗
const addRent = async (id: number) => {
  // 设置企业id,用于添加合同
  rentForm.value.enterpriseId = id;
  rentDialogVisible.value = true;
  // 获取楼宇下拉列表
  const res = await getRentBuildListAPI();
  // console.log('res',res)
  buildList.value = res.data;
};

const fileList = ref<UploadUserFile[]>([]);
// 关闭弹窗
const closeRent = () => {
  // 清空表单校验
  addFormRef.value?.clearValidate();
  // 关闭弹窗
  rentDialogVisible.value = false;
  // 清空数组表单
  timeArr.value = [];
  // 清空上传文件列表
  fileList.value = [];
  // 主动重置数据
  rentForm.value = initRentForm();
};

const timeArr = ref<string[]>([]);
// 监听时间选择器
watch(
  timeArr,
  (val) => {
    if (val) {
      rentForm.value.startTime = val[0];
      rentForm.value.endTime = val[1];
    } else {
      rentForm.value.startTime = '';
      rentForm.value.endTime = '';
    }
  },
  { deep: true }
);
// 通过 disabledDate 函数，限制日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};

const addFormRef = ref<FormInstance>();

// 上传合同文件
const onUploadRequest = async (options: UploadRequestOptions) => {
  // 1. 准备 FormData 对象
  const fd = new FormData();
  fd.append('file', options.file); // 文件
  fd.append('type', 'contract'); // 类型
  // 2. 调用上传接口
  const res = await uploadAPI(fd);
  // console.log('res', res);
  // 保存合同附件url和id,用于添加合同
  rentForm.value.contractUrl = res.data.url;
  rentForm.value.contractId = res.data.id;
  // 3. 调用表单校验
  addFormRef.value?.validateField('contractId');
  return;
};

// 删除上传文件
const removeUpload = () => {
  rentForm.value.contractUrl = '';
  rentForm.value.contractId = undefined;
  addFormRef.value?.clearValidate('contractId');
  console.log(addFormRef.value);
};

// 上传前校验文件大小
const beforeUpload = (rawFile: UploadRawFile) => {
  const allowSize = 1 * 1024 * 1024;
  if (rawFile.size > allowSize) {
    ElMessage.error('上传文件大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 添加合同
const addRentConfirm = async () => {
  try {
    // 校验表单
    await addFormRef.value?.validate();
    // 添加合同
    await createRentAPI(rentForm.value);
    ElMessage.success('添加合同成功');
    // 关闭弹窗
    // rentDialogVisible.value = false;
    // 关闭弹窗,调用刚刚写好的方法
    closeRent();
    // 刷新列表
    getList();
  } catch (error) {
    // console.log(error);
  }
};

const rentList = ref<Enterprise[]>([]);

// 展开行触发
const onExpandChange = async (row: EnterpriseWithRent) => {
  // 根据企业 id 获取合同列表
  const res = await getRentListAPI(row.id);
  // 把合同列表添加到企业信息中
  row.rentList = res.data;
};


    // 退租合同
    const outRent = (row: Datum) => {
    ElMessageBox.confirm('退租不可撤回，是否确认退租当前楼宇?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 发送请求，更新后端合同状态 
      await outRentAPI(row.id)
      console.log(row,'想要');
      
      // 更新前端合同状态，退租按钮变禁用
      row.status = 3
      // 轻提示
      ElMessage.success('退租成功')
    }).catch(() => {
      // 点击取消，什么也不做
    })
  }

// 删除合同
const deleteRent = (rentRow: Datum, fatherRow: EnterpriseWithRent) => {
  ElMessageBox.confirm('删除不可撤回，是否确认删除当前合同?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，更新后端的状态
    await deleteRentAPI(rentRow.id)
    // 删除过滤掉合同（前端）
    fatherRow.rentList = fatherRow.rentList.filter(item => item.id !== rentRow.id)
    // 轻提示
    ElMessage.success('删除成功')

  }).catch(()=>{

  })
}

</script>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
